﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ScrumTime.Models;


namespace ScrumTime.Helpers
{
    public class InitialData
    {
        const String DEFAULT_USER_NAME = "admin";
        const String DEFAULT_USER_PASSWORD = "password";
        const String DEFAULT_USER_MAIL = "admin@admin.com";
        const String DEFAULT_PRODUCT_NAME = "New Product";


        ScrumTimeEntities context;


        public static void CheckInitialData() {
            InitialData ini = new InitialData();
            ini.pCheckInitialData();
        }


        private InitialData() { 
            context= new ScrumTimeEntities();  
        }

        private void pCheckInitialData() {

            ChechUserDefault();


            CheckProduct();

            context.SaveChanges();
        }

        private void ChechUserDefault()
        {
            if (setDefaultUser())
            {
                AccountMembershipService membershipService = new AccountMembershipService();
                System.Web.Security.MembershipUser user = getUser(DEFAULT_USER_NAME, membershipService);

                if (user == null)
                {
                    CreateNewAdmin(membershipService);
                }
                else
                {
                    UpdateAdmin(user);
                    System.Web.Security.Membership.UpdateUser(user); 
                }         
            }
        }

        private void UpdateAdmin(System.Web.Security.MembershipUser user)
        {
            ResetPassword(user);

            AddAdminRol(user);
        }

        private void AddAdminRol(System.Web.Security.MembershipUser user)
        {
            ScrumTime.Services.UserService userService = new ScrumTime.Services.UserService(context);
            User u = userService.GetUserByGuid(user.ProviderUserKey.ToString());
            u.Roles.Clear();
            u.Roles.Add(GetRolAdmin());
        }

        private static void ResetPassword(System.Web.Security.MembershipUser user)
        {
            String newPassword = user.ResetPassword();
            user.ChangePassword(newPassword, DEFAULT_USER_PASSWORD);
        }

        private void CreateNewAdmin(AccountMembershipService membershipService)
        {
            System.Web.Security.MembershipCreateStatus mcs = membershipService.CreateUser(DEFAULT_USER_NAME, DEFAULT_USER_PASSWORD, DEFAULT_USER_MAIL);
            if (mcs != System.Web.Security.MembershipCreateStatus.Success)
            {
                throw new Exception(mcs.ToString());
            }

            //creamos el usuario
            ScrumTime.Models.User new_user = new ScrumTime.Models.User();

            String userId = getUserId(DEFAULT_USER_NAME, membershipService);
            new_user.UserId = new Guid(userId);
            new_user.UserName = DEFAULT_USER_NAME;
            new_user.Roles.Add(GetRolAdmin());
        }


        private ScrumTime.Models.Role GetRol(int rolId)
        {
            ScrumTime.Models.Role resultado = null;
            foreach (Role r in context.Roles)
            {
                if (r.RolId == rolId)
                {
                    resultado = r;
                    break;
                }
            }
            return resultado;
        }

        private ScrumTime.Models.Role GetRolAdmin()
        {
            int rolAdmin = ScrumTime.Helpers.ScrumTimeAppConfig.GetUserId_Admin();            
            return GetRol(rolAdmin);
        }

        private string getUserId(string name, AccountMembershipService membershipService)
        {
            String resultado = name;
            name = name.ToString();
            System.Web.Security.MembershipUserCollection userCollection = membershipService.GetAllUsers();

            foreach (System.Web.Security.MembershipUser user in userCollection)
            {
                if (user.UserName == name)
                {
                    resultado = user.ProviderUserKey.ToString();
                    break;
                }
            }
            return resultado;
        }

        private bool setDefaultUser()
        {
            return ScrumTime.Helpers.ScrumTimeAppConfig.GetSetUserDefault();
        }
       

        #region "metodos auxiliares"

        private System.Web.Security.MembershipUser getUser(String username, AccountMembershipService accountService)
        {
            System.Web.Security.MembershipUser resultado = null;
            foreach (System.Web.Security.MembershipUser user in accountService.GetAllUsers())
            {
                if (username == user.UserName)
                {
                    resultado = user;
                    break;
                }
            }
            return resultado;
        }

        private void CheckProduct()
        {
            if (!existAnyProduct())
            {
                Product product = CreateProduct();
                context.AddToProducts(product);
            }
        }

        private static Product CreateProduct()
        {
            Product product = new Product()
            {
                Name = "New Product",
                Description = "Initial product created by the application.",
            };
            return product;
        }

        private bool existAnyProduct() {
            return context.Products.Count() > 0;
        }

        #endregion

    }
}